package com.cgs.springboottes2secrity.secfilter;

import com.cgs.springboottes2secrity.sec.JwtToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cgs
 * @version woNiu 98
 * @date 2023/5/12 15:23
 */
public class JwtVerifyFilter extends AbstractAuthenticationProcessingFilter {
    public JwtVerifyFilter(String defaultFilterProcessesUrl) {
        super(defaultFilterProcessesUrl);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            attemptAuthentication((HttpServletRequest) request, (HttpServletResponse) response);
            chain.doFilter(request,response);
        }catch (AuthenticationException a){
            throw a;
        }
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        //从请求头中获取到JWT
        String jwt = request.getHeader("Authorization");

        JwtToken jwtToken = new JwtToken(null , jwt);

        return this.getAuthenticationManager().authenticate(jwtToken);
    }
}